package cn.net.wanji.entity;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class UserSimulator {

    private final RestTemplate restTemplate;
    private final ExecutorService executorService;

//    @Autowired
    public UserSimulator(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
        this.executorService = Executors.newFixedThreadPool(5); // 创建一个含有5个线程的线程池
    }

//    @PostConstruct
    public void simulateUsers() {
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            executorService.execute(() -> {
                // 创建请求的参数
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                // 构造请求体
                JsonRoot jsonRoot = new JsonRoot();

                jsonRoot.setERID("0000");
                jsonRoot.setRecordId(String.valueOf(finalI));
                jsonRoot.setRecordType("1");

                System.out.println(jsonRoot);
//                if (jsonRoot == null || jsonRoot.getRecordId() == null) {
//                    return AjaxResult.error("jsonRoot is null");
//                }
                HttpEntity<JsonRoot> request = new HttpEntity<>(jsonRoot, headers);

                // 发送 POST 请求
//                try {
//                    Thread.sleep(10);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
                String response = restTemplate.postForObject("http://127.0.0.1:9092/receive/data", request, String.class);
                System.out.println("User response: " + response);
            });
        }
        executorService.shutdown(); // 关闭线程池
    }

    public static void main(String[] args) {
        UserSimulator userSimulator = new UserSimulator(new RestTemplate());
        userSimulator.simulateUsers();
    }
}

